package com.yunquan.ohana.ui.home

import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.ui.BaseFragment
import com.yunquan.ohana.databinding.FragmentHomeBinding
import com.yunquan.ohana.entity.FramesEntity
import com.yunquan.ohana.ui.home.calendar.CalendarFragment
import com.yunquan.ohana.ui.home.frames.FramesFragment
import com.yunquan.ohana.ui.home.frames.dialog.InvitationCodeDialog
import com.yunquan.ohana.ui.photos.PhotosActivity
import com.yunquan.ohana.ui.scan.ScanActivity
import com.yunquan.ohana.ui.selectFrames.SelectFramesActivity
import com.yunquan.ohana.utils.Utils

class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>() {

    companion object {
        fun newInstance(): HomeFragment {
            return HomeFragment()
        }
    }

    private var menuDialog: PopupWindow? = null

    // 这里处理返回结果
    private val mActivityResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == ScanActivity.RESULT_CODE) {
            // 扫描二维码返回
            val bundle = result.data?.extras
            val text = bundle?.getString("text")
            text?.let {
                viewModel!!.bindFrames(it)
            }
        } else if (result.resultCode == SelectFramesActivity.RESULT_CODE) {
            // 获取相框返回
            val bundle = result.data?.extras
            val framesJson = bundle?.getString("frames")
            val listType = object : TypeToken<List<FramesEntity>>() {}.type
            val frames: List<FramesEntity> = Gson().fromJson(framesJson, listType)
            goToAlbum(frames)
        }
    }

    override fun initContentView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): Int {
        return R.layout.fragment_home
    }

    override fun initVariableId(): Int {
        return BR.homeViewModel
    }

    override fun initData(savedInstanceState: Bundle?) {
        val titles = listOf(
            R.string.tab_frame,
            R.string.tab_calendar,
        )
        val fragments = listOf(
            FramesFragment.newInstance(),
            CalendarFragment.newInstance(),
        )
        binding!!.vpContent.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int = fragments.size
            override fun createFragment(position: Int) = fragments[position]
        }
        TabLayoutMediator(binding!!.tlHomeTabs, binding!!.vpContent) { tab, position ->
            tab.text = getString(titles[position])
        }.attach()
    }

    override fun initViewObservable() {
        super.initViewObservable()
        binding!!.btnScan.setOnClickListener {
            val intent = Intent(requireContext(), ScanActivity::class.java)
            mActivityResult.launch(intent)
        }
        binding!!.btnSend.setOnClickListener {
            val intent = Intent(requireContext(), SelectFramesActivity::class.java)
            mActivityResult.launch(intent)
        }
        binding!!.btnAddFrames.setOnClickListener {
            showMenuDialog()
        }
    }

    /**
     * 显示绑定弹窗
     */
    private fun showMenuDialog() {
        if (menuDialog == null) {
            val view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_frames_menu, null)
            view.findViewById<TextView>(R.id.btn_scan).setOnClickListener {
                val intent = Intent(requireContext(), ScanActivity::class.java)
                mActivityResult.launch(intent)
                menuDialog?.dismiss()
            }
            view.findViewById<TextView>(R.id.btn_invitation_code).setOnClickListener {
                val dialog = InvitationCodeDialog(requireContext())
                dialog.setOnCallback(object : InvitationCodeDialog.OnCallback {
                    override fun call(code: String) {
                        viewModel!!.bindFrames(code)
                    }
                })
                dialog.show()
                menuDialog?.dismiss()
            }
            menuDialog = PopupWindow(requireContext())
            menuDialog!!.contentView = view
            menuDialog!!.width = Utils.instance.dp2px(130f)
            menuDialog!!.height = ViewGroup.LayoutParams.WRAP_CONTENT
            menuDialog!!.isOutsideTouchable = true
            menuDialog!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        }
        val xoff = Utils.instance.dp2px(-86f)
        menuDialog?.showAsDropDown(binding!!.btnAddFrames, xoff, 32)
    }


    /**
     * 跳转相册选择
     */
    private fun goToAlbum(frames: List<FramesEntity>) {
        val framesJson = Gson().toJson(frames)
        val bundle = Bundle()
        bundle.putString("frames", framesJson)
        startActivity(PhotosActivity::class.java, bundle)
    }
}